package com.customization.gyxy;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.workflow.cmd.requestForm.RequestSubmitCmd;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.gyxy.rabbitmq.util.SendMessagesUtil;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


/**
 * @Classname CustomRequestSubmitCmd
 * @Description TODO()
 * @Author dusongsong
 * @Date 2023-11-09 14:49
 **/


@CommandDynamicProxy(target = RequestSubmitCmd.class, desc = "流程提交后给调用接口")
public class CustomRequestSubmitCmd extends AbstractCommandProxy<Map<String, Object>> {
    @Override
    public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
        //获取到被代理对象
        RequestSubmitCmd requestSubmitCmd = (RequestSubmitCmd) targetCommand;
        //获取被代理对象的参数
        Map<String, Object> params = requestSubmitCmd.getParams();
        //参数回写
        requestSubmitCmd.setParams(params);
        //执行标准的业务处理
        Map<String, Object> result = nextExecute(targetCommand);
        //对返回值做加工处理
        RequestOperationResultBean resultBean = (RequestOperationResultBean) result.get("data");
        String executeResult = resultBean.getType().name();
        requestSubmitCmd.writeLog("requestSubmitCmd executeResult======" + executeResult);
        if ("SUCCESS".equals(executeResult)) {
            HttpServletRequest request = requestSubmitCmd.getRequest();
            User user = requestSubmitCmd.getUser();
            String nodeid = (String) params.get("nodeid");
            requestSubmitCmd.writeLog("requestSubmitCmd nodeid======" + nodeid);
            String requestid = (String) params.get("requestid");
            requestSubmitCmd.writeLog("requestSubmitCmd requestid======" + requestid);
            if (Util.getIntValue(requestid) > 0) {
                RequestService requestService = new RequestService();
                RequestInfo requestInfo = requestService.getRequest(Integer.parseInt(requestid));
                String requestname = requestInfo.getRequestManager().getRequestname();
                int workflowid = requestInfo.getRequestManager().getWorkflowid();
                String fullDate = DateUtil.getFullDate();
                //推送门户消息
                JSONObject operatorInfo = getOperatorInfo(requestid, nodeid);
                String signorder = operatorInfo.getString("signorder");
                if ("0".equals(signorder)) {

                    requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>非会签");
                    String userids = operatorInfo.getString("userids");
                    String[] useridArr = userids.split(",");
                    SendMessagesUtil sendMessagesUtil = new SendMessagesUtil();
                    try {
                        ResourceComInfo comInfo = new ResourceComInfo();
                        for (String userid : useridArr) {
                            String loginid = comInfo.getLoginID(userid);
                            String pcurl = "http://xtbg.wxgyxy.edu.cn/login/ssoTogyxy.jsp?loginid=" + loginid + "&requestid=" + requestid;
                            String emurl = "http://ydoa.wxgyxy.edu.cn:9000/login/ssoTogyxyEM.jsp?loginid=" + loginid + "&requestid=" + requestid;
                            //发送流程实例
                            //流程ID
                            String lcid_instance = requestid + userid + "oa";
                            //事项ID （每个事项唯一的ID）
                            String sxid_instance = requestid + userid;
                            //事项名称
                            String sxmc_instance = getWorkflowname(workflowid);
                            //标题说明
                            String btsm_instance = requestname;
                            //申请时间 （格式：yyyy-MM-dd HH:mm:ss）
                            String sqsj_instance = fullDate;
                            //持续时间
                            JSONObject resultJson = getReceivedate(requestid, nodeid, Util.getIntValue(userid));
                            String operaterDate = Util.null2String(resultJson.getString("operatedatetime"));
                            String receiveDate = Util.null2String(resultJson.getString("receivedatetime"));
                            String cxsj_instance = getDayHourMinute(receiveDate, operaterDate);
                            //申请人（教工号或学号）
                            String sqr_instance = loginid;
                            //流程地址
                            String url_instance = pcurl;
                            //业务系统
                            String source_instance = "oa";
                            //流程状态1:进行中 2:已完成 3:草稿 4:已删除
                            String status_instance = "2";
                            //任务结果1:审批中 2:已撤销 3:以驳回 4:审核通过 5:审核不通 6:逻辑删除，7:草稿，8：删除
                            String result_instance = "4";
                            //是否有手机表单（1：有  2：没有）
                            String hasmobile_instance = "1";
                            //手机办理地址 （填写相对地址，地址前加/）
                            String mobileurl_instance = emurl;
                            //办结时间 （格式：yyyy-MM-dd HH:mm:ss）
                            String bjsj_instance = fullDate;
                            String instanceMessage = sendMessagesUtil.sendProcessInstance(lcid_instance, sxid_instance, sxmc_instance, btsm_instance, sqsj_instance,
                                    cxsj_instance, sqr_instance, url_instance, source_instance, status_instance,
                                    result_instance, hasmobile_instance, mobileurl_instance, bjsj_instance);
                            requestSubmitCmd.writeLog(">>>>>CustomRequestSubmitCmd>>>>>instanceMessage=" + instanceMessage);

                            //发送流程任务
                            //流程ID （每条流程唯一的ID）
                            String lcid_task = requestid + userid + "oa";
                            //节点ID（当前流程的每个节点唯一的ID）
                            String jdid_task = nodeid;
                            //标题说明（当前任务的标题说明）
                            String btsm_task = requestname;
                            //办理地址 （填写相对地址，地址前加/）
                            String bldz_task = pcurl;
                            //流程跟踪地址 （填写相对地址，地址前加/）
                            String lcgzdz_task = pcurl;
                            //当前节点 （当前流程的每个节点唯一的名称）
                            String dqjd_task = getNodename(nodeid);
                            //使用角色 （当前审批人使用的角色）
                            String syjs_task = loginid;
                            //查阅状态 （1:已阅 2：未阅）
                            String cyzt_task = "2";
                            //任务状态 1: 进行中 2: 已完成 3：已撤销 4: 转发
                            String status_task = "2";
                            //任务结果1: 审核中 2: 审核通过 3: 审核不通过 4: 已撤销 5: 略过，6 :转发
                            String result_task = "2";
                            //是否有手机表单（1：有  2：没有）
                            String hasmobile_task = "1";
                            //手机办理地址 （填写相对地址，地址前加/）
                            String mobileurl_task = emurl;
                            //任务处理时间 （格式：yyyy-MM-dd HH:mm:ss）
                            String clsj_task = fullDate;
                            String[] sprs = new String[]{loginid};
                            String taskMessagePass = sendMessagesUtil.sendProcessTask(lcid_task, jdid_task, btsm_task, bldz_task, sprs, lcgzdz_task,
                                    dqjd_task, syjs_task, cyzt_task, status_task, result_task, hasmobile_task,
                                    mobileurl_task, clsj_task);
                            requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>taskMessagePass=" + taskMessagePass);
                            String result_task1 = "5";
                            String taskMessageIgnore = sendMessagesUtil.sendProcessTask(lcid_task, jdid_task, btsm_task, bldz_task, sprs, lcgzdz_task,
                                    dqjd_task, syjs_task, cyzt_task, status_task, result_task1, hasmobile_task,
                                    mobileurl_task, clsj_task);
                            requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>taskMessageIgnore=" + taskMessageIgnore);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    String loginId = user.getLoginid();
                    requestSubmitCmd.writeLog("requestSubmitCmd user======" + loginId);
                    String pcurl = "http://xtbg.wxgyxy.edu.cn/login/ssoTogyxy.jsp?loginid=" + loginId + "&requestid=" + requestid;
                    String emurl = "http://ydoa.wxgyxy.edu.cn:9000/login/ssoTogyxyEM.jsp?loginid=" + loginId + "&requestid=" + requestid;
                    requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>会签");
                    SendMessagesUtil sendMessagesUtil = new SendMessagesUtil();
                    //发送流程实例
                    //流程ID
                    String lcid_instance = requestid + user.getUID() + "oa";
                    //事项ID （每个事项唯一的ID）
                    String sxid_instance = requestid + user.getUID();
                    //事项名称
                    String sxmc_instance = getWorkflowname(workflowid);
                    //标题说明
                    String btsm_instance = requestname;
                    //申请时间 （格式：yyyy-MM-dd HH:mm:ss）
                    String sqsj_instance = fullDate;
                    //持续时间
                    JSONObject resultJson = getReceivedate(requestid, nodeid, user.getUID());
                    String operaterDate = Util.null2String(resultJson.getString("operatedatetime"));
                    String receiveDate = Util.null2String(resultJson.getString("receivedatetime"));
                    String cxsj_instance = getDayHourMinute(receiveDate, operaterDate);
                    //申请人（教工号或学号）
                    String sqr_instance = loginId;
                    //流程地址
                    String url_instance = pcurl;
                    //业务系统
                    String source_instance = "oa";
                    //流程状态1:进行中 2:已完成 3:草稿 4:已删除
                    String status_instance = "2";
                    //任务结果1:审批中 2:已撤销 3:以驳回 4:审核通过 5:审核不通 6:逻辑删除，7:草稿，8：删除
                    String result_instance = "4";
                    //是否有手机表单（1：有  2：没有）
                    String hasmobile_instance = "1";
                    //手机办理地址 （填写相对地址，地址前加/）
                    String mobileurl_instance = emurl;
                    //办结时间 （格式：yyyy-MM-dd HH:mm:ss）
                    String bjsj_instance = fullDate;
                    String instanceMessage = sendMessagesUtil.sendProcessInstance(lcid_instance, sxid_instance, sxmc_instance, btsm_instance, sqsj_instance,
                            cxsj_instance, sqr_instance, url_instance, source_instance, status_instance,
                            result_instance, hasmobile_instance, mobileurl_instance, bjsj_instance);
                    requestSubmitCmd.writeLog(">>>>>CustomRequestSubmitCmd>>>>>instanceMessage=" + instanceMessage);

                    //发送流程任务
                    //流程ID （每条流程唯一的ID）
                    String lcid_task = requestid + user.getUID() + "oa";
                    //节点ID（当前流程的每个节点唯一的ID）
                    String jdid_task = nodeid;
                    //标题说明（当前任务的标题说明）
                    String btsm_task = requestname;
                    //办理地址 （填写相对地址，地址前加/）
                    String bldz_task = pcurl;
                    //流程跟踪地址 （填写相对地址，地址前加/）
                    String lcgzdz_task = pcurl;
                    //当前节点 （当前流程的每个节点唯一的名称）
                    String dqjd_task = getNodename(nodeid);
                    //使用角色 （当前审批人使用的角色）
                    String syjs_task = loginId;
                    //查阅状态 （1:已阅 2：未阅）
                    String cyzt_task = "2";
                    //任务状态 1: 进行中 2: 已完成 3：已撤销 4: 转发
                    String status_task = "2";
                    //任务结果1: 审核中 2: 审核通过 3: 审核不通过 4: 已撤销 5: 略过，6 :转发
                    String result_task = "2";
                    //是否有手机表单（1：有  2：没有）
                    String hasmobile_task = "1";
                    //手机办理地址 （填写相对地址，地址前加/）
                    String mobileurl_task = emurl;
                    //任务处理时间 （格式：yyyy-MM-dd HH:mm:ss）
                    String clsj_task = fullDate;
                    String[] sprs = new String[]{loginId};
                    String taskMessagePass = sendMessagesUtil.sendProcessTask(lcid_task, jdid_task, btsm_task, bldz_task, sprs, lcgzdz_task,
                            dqjd_task, syjs_task, cyzt_task, status_task, result_task, hasmobile_task,
                            mobileurl_task, clsj_task);
                    requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>taskMessagePass=" + taskMessagePass);
                    String result_task1 = "5";
                    String taskMessageIgnore = sendMessagesUtil.sendProcessTask(lcid_task, jdid_task, btsm_task, bldz_task, sprs, lcgzdz_task,
                            dqjd_task, syjs_task, cyzt_task, status_task, result_task1, hasmobile_task,
                            mobileurl_task, clsj_task);
                    requestSubmitCmd.writeLog(">>>>CustomRequestSubmitCmd>>>>>taskMessageIgnore=" + taskMessageIgnore);

                }

            }
        }
        return result;
    }

    //获取节点名称
    public static String getNodename(String nodeid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select nodename from workflow_nodebase where id=?", nodeid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    //获取流程名称
    public static String getWorkflowname(int workflowid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery(" select workflowname from workflow_base where id=?", workflowid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    //获取接收时间
    public static JSONObject getReceivedate(String requestid, String nodeid, int userid) {
        RecordSet rs = new RecordSet();
        JSONObject jsonObject = new JSONObject();
        String sql = "select max(concat(concat(operatedate,' '),operatetime)) operatedatetime,max(concat(concat(receivedate,' '),receivetime)) receivedatetime " +
                "from workflow_currentoperator where requestid=? and nodeid=? and userid=?";
        rs.executeQuery(sql, requestid, nodeid, userid);
        rs.next();
        jsonObject.put("operatedatetime", Util.null2String(rs.getString("operatedatetime")));
        jsonObject.put("receivedatetime", Util.null2String(rs.getString("receivedatetime")));
        return jsonObject;
    }

    public static String getDayHourMinute(String datetime1, String datetime2) {
        String datetime = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(datetime1);
            Date date2 = sdf.parse(datetime2);
            // 获取时间戳
            long timestamp1 = date1.getTime();
            long timestamp2 = date2.getTime();

            // 计算两个时间戳的差值
            long diff = Math.abs(timestamp1 - timestamp2);

            // 计算天数
            long days = diff / (24 * 60 * 60 * 1000);

            // 计算小时数
            long hours = (diff / (60 * 60 * 1000)) % 24;

            // 计算分钟数
            long minutes = (diff / (60 * 1000)) % 60;

            // 计算秒数
            long seconds = (diff / 1000) % 60;

            // 打印结果
            datetime = days + "天" + hours + "小时" + minutes + "分钟";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datetime;
    }

    public static JSONObject getOperatorInfo(String requestid, String nodeid) {
        RecordSet rs = new RecordSet();
        String signorder = "";
        String userids = "";
        JSONObject jsonObject = new JSONObject();
        try {

            rs.executeQuery("select userid,(select t.signorder from workflow_groupdetail t where t.id=groupdetailid) signorder\n" +
                    " from workflow_currentoperator where requestid=? and nodeid=? " +
                    "group by userid,groupdetailid", requestid, nodeid);
            while (rs.next()) {
                String userid = Util.null2String(rs.getString("userid"));
                userids += "".equals(userids) ? userid : "," + userid;
                signorder = Util.null2String(rs.getString("signorder"));
            }
            jsonObject.put("signorder", signorder);
            jsonObject.put("userids", userids);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
